package drds.global_transaction.api.rpc.rpc_message;

import lombok.Getter;
import lombok.Setter;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class RpcInfoFuture
{
	private static final Object NULL = new Object();
	private final CountDownLatch countDownLatch = new CountDownLatch(1);

	@Setter
	@Getter
	private RpcInfo rpcInfo;
	@Setter
	@Getter
	private long timeout;
	@Setter
	@Getter
	private boolean timeOutMark = false;
	@Setter
	@Getter
	private long startDateTimeLong = System.currentTimeMillis();
	@Setter
	@Getter
	private volatile Object responseMessage;

	//
	public boolean isTimeout()
	{
		return System.currentTimeMillis() - startDateTimeLong > timeout;
	}

	//
	public void setResponseMessage(Object object)
	{
		this.responseMessage = (object == null ? NULL : object);
		countDownLatch.countDown();
	}

	//
	public Object get(long timeout, TimeUnit timeUnit) throws TimeoutException, InterruptedException
	{
		boolean success = countDownLatch.await(timeout, timeUnit);
		if (!success)
		{
			throw new TimeoutException("cost " + (System.currentTimeMillis() - startDateTimeLong) + " ms");
		}
		if (responseMessage instanceof RuntimeException)
		{
			throw (RuntimeException) responseMessage;
		} else if (responseMessage instanceof Throwable)
		{
			throw new RuntimeException((Throwable) responseMessage);
		}
		return responseMessage;
	}

}
